package com.tool.weixin.api;

import net.sf.json.JSONObject;

import org.slf4j.Logger;

import com.tool.weixin.enums.MediaTypeEnum;
import com.tool.weixin.util.HttpUtils;

public class MediaApi {

	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(MediaApi.class);
	/**上传临时素材**/
	private static final String media_upload_url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
	/**下载临时素材**/
	private static final String media_down_url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
	
	/**
	 * 上传临时素材
	 * @param type 文件类型
	 * @param filepath 文件路径
	 * @return mediaid 媒体文件ID
	 */
	public static String uploadMedia(MediaTypeEnum typeEnum,String filepath) {
		String url = media_upload_url.replace("ACCESS_TOKEN", AccessTokenApi.getAccessToken().getToken()).replace("TYPE", typeEnum.name);
		JSONObject jsonObject = HttpUtils.uploadFile(url, filepath);
		String mediaid = null;
		if(jsonObject != null) {
			try {
				mediaid = jsonObject.getString("media_id");
			} catch (Exception e) {
				logger.error("上传临时素材失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return mediaid;
	}
	
	/**
	 * 下载临时素材
	 * @param mediaid 媒体文件ID
	 * @param type 文件类型
	 * @param filepath 文件路径
	 * @return
	 */
	public static String downMedia(String mediaid,MediaTypeEnum typeEnum,String filepath) {
		String url = media_down_url.replace("ACCESS_TOKEN", AccessTokenApi.getAccessToken().getToken()).replace("MEDIA_ID", mediaid);
		JSONObject jsonObject = HttpUtils.downFile(url, filepath, typeEnum.name);
		String filename = null;
		if(jsonObject != null) {
			try {
				filename = jsonObject.getString("filename");
			} catch (Exception e) {
				logger.error("上传临时素材失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return filename;
	}
	
	
}
